//
//  ProgressController.m
//  BSProject
//
//  Created by nsm on 2019/10/19.
//  Copyright © 2019 beisheng. All rights reserved.
//

#import "ProgressController.h"
#import "LoadingProgressView.h"

#pragma mark - 扩展一个ProgressLayer
static const CGFloat kCircleWidth = 40.0f;
@interface LoadingProgressLayer : CALayer
@property (nonatomic) CGFloat progress;
@property (nonatomic, strong) CAShapeLayer *progressLayer;
@end

@implementation LoadingProgressLayer
- (instancetype)init {
    self = [super init];
    if (self) {
        [self initialize];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self initialize];
    }
    return self;
}

- (void)layoutSublayers {
    [super layoutSublayers];
    
    _progressLayer.frame = self.bounds;
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(0, self.height/2)];
    [path addLineToPoint:CGPointMake(self.width, self.height/2)];
    path.lineCapStyle = kCGLineCapRound;
    
    _progressLayer.path = path.CGPath;
    _progressLayer.lineWidth = self.height;
}

- (void)initialize {
    CGFloat kBorderWidth = 2.f;
    CGFloat radius = kCircleWidth / 2;
    UIColor *kBorderColor = UIColor.blackColor;
    UIColor *kBackgroundColor = UIColor.redColor;
    UIColor *kProgressColor = UIColor.whiteColor;
    
    _progress = 0;
    
    self.backgroundColor = kBackgroundColor.CGColor;
    self.cornerRadius = radius;
    self.borderWidth = kBorderWidth;
    self.borderColor = kBorderColor.CGColor;
    self.masksToBounds = YES;

    _progressLayer = [CAShapeLayer layer];
    _progressLayer.fillColor = UIColor.clearColor.CGColor;
    _progressLayer.strokeColor = kProgressColor.CGColor;
    _progressLayer.strokeStart = 0;
    _progressLayer.strokeEnd = 0;
    [self addSublayer:_progressLayer];
}

- (void)setProgress:(CGFloat)progress {
    _progress = progress<0? 0: (progress>1? 1: progress);
    
    _progressLayer.strokeEnd = _progress;
}

@end

@interface ProgressController ()

@end

@implementation ProgressController

#pragma mark - lifeCycle

#pragma mark - override

#pragma mark - initialization
- (void)viewDidLoad {
    [super viewDidLoad];
    
    LoadingProgressView *view = LoadingProgressView.new;
    view.frame = CGRectMake(100, 200, 200, 40);
    [self.view addSubview:view];
    ViewCorner(view, view.height/2);
    ViewBorder(view, 5, UIColor.blackColor);
    
    view.progress = 0.6;
}

#pragma mark - setter/getter

#pragma mark - network

#pragma mark - method/public

#pragma mark - method/private

#pragma mark - action

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
